import { message } from 'antd'
import axios from 'axios'
import { getToken, hasToken, removeToken } from 'utils/storage'
import { history } from './history'

const instance = axios.create({
  baseURL: 'http://geek.itheima.net/',
  timeout: 5000,
})

// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    // console.log('请求拦截器', config)
    if (hasToken()) {
      config.headers.Authorization = 'Bearer ' + JSON.parse(getToken()).token
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  function (res) {
    // console.log(res);
    return res.data.data
  },
  function (error) {
    if (error.response && error.response.status === 401) {
      removeToken()
      history.push('/login')
      // history.go(0)
      message.warning('登录过期，请重新登录')
    }
    return Promise.reject(error)
  }
)

export default instance
